import Vue from 'vue'
import xurl from './xurl'
import XCookie from './XCookie'
import browser from '../../static/js/browser'
import XTrade from './XTrade'
import XParams from './XParams'

export default {
//---------------------------------去支付---------------------------------/
    /**
     * 获得支付渠道
     * @returns {string}
     */
    getPayChannel() {
        if (browser.is_weixin()) {
            return 'WECHAT';
        } else if (browser.is_alipay()) {
            return 'ALIPAY';
        } else if (browser.is_mobile_web()) {
            //TODO 这里应该让用户选择  微信 or 支付宝
            return 'WECHAT_WEB';
        }
        return 'ALIPAY';
    },
    getPayChannelName(payChannel) {
        switch (payChannel) {
            case 'WECHAT':
                return "微信支付"
            case 'WECHAT_WEB':
                return "微信支付"
            case 'ALIPAY':
                return "支付宝支付"
        }
        return "其他"
    },
    /**
     * 去支付
     */
    toPay(params) {
        if (Object.keys(params).length == 0) {
            return;
        }
        switch (params.payChannel) {
            case  'WECHAT' :
                this.toPayByWechat(params)
                break;
            case  'WECHAT_WEB' :
                this.toPayByWechatWeb(params)
                break;
            case  'ALIPAY':
                this.toPayByAlipay(params)
                break;
        }
    },
    /**
     * 已有订单点击去支付
     */
    payOrder(orderNum) {
        let url = Vue.prototype.NW_API_vue + '/confirm/detailOrder?orderNum=' + orderNum + '&payChannel=' + this.getPayChannel()
        if (XCookie.existPayOpenId()) {
            url += "&payOpenId=" + XCookie.getPayOpenId()
        }
        console.log("url = " + url)
        xurl.getLoading(url).then((data) => {
            // localStorage.setItem("1111dddd" + url, JSON.stringify(data))
            // localStorage.setItem("1111dddd" + url, null)
            let href = data.result.href
            let redirect = data.result.redirect
            let payChannel = data.result.payChannel
            if (href != null) {
                window.location.href = href
            } else if (redirect != null) {
                if (redirect == '/trade/procure/confirmProcure') {
                    XTrade.updateConfirmProcureParam(data.result)
                    window.location.href = redirect
                } else {
                    window.location.href = redirect + XParams.getParams(data.result)
                }
            } else if (!!payChannel) {
                this.toPay(data.result);
            }
        })
    },
    /**
     * 订单再次付款
     */
    payOrderAgain(orderNum) {
        let url = Vue.prototype.NW_API_vue + "/confirm/payOrderAgain?orderNum=" + orderNum + "&payChannel=" + this.getPayChannel()
        if (XCookie.existPayOpenId()) {
            url += "&payOpenId=" + XCookie.getPayOpenId()
        }
        xurl.getLoading(url).then((data) => {
            if (data.success) {
                let href = data.result.href
                let redirect = data.result.redirect
                let payChannel = data.result.payChannel
                if (href != null) {
                    window.location.href = href
                } else if (redirect != null) {
                    if (redirect == '/trade/procure/confirmProcure') {
                        XTrade.updateConfirmProcureParam(data.result)
                        window.location.href = redirect
                    } else {
                        window.location.href = redirect + XParams.getParams(data.result)
                    }
                } else if (!!payChannel) {
                    this.toPay(data.result)
                }
            } else {
                window.location.href = "/error?msg=" + err.message
            }
        })
    },
    /**
     * 去支付 by alipay
     */
    toPayByAlipay(params) {
        let payParams = {
            out_trade_no: params.tradeNo,
            total_fee: params.totalFee,
            subject: params.subject
        };

        let url = Vue.prototype.NW_API_API_LOCALE_VERSION + "/h5/pay/ali";
        console.log(url)
        xurl.postLoading(url, payParams).then((data) => {
            console.log("data : " + JSON.stringify(data))
            document.write(data.result);
        })
    },
    /**
     * 去支付 by 微信客户端
     */
    toPayByWechat(params) {
        let appId = params.appId;
        let timeStamp = params.timeStamp;
        let nonceStr = params.nonceStr;
        let packageStr = params.packageStr;
        let signType = params.signType;
        let paySign = params.paySign;
        let payOrderNum = params.payOrderNum;
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        } else {
            onBridgeReady();
        }

        function onBridgeReady() {
            let params = {
                "appId": appId,     //公众号名称，由商户传入
                "timeStamp": timeStamp,         //时间戳，自1970年以来的秒数
                "nonceStr": nonceStr, //随机串
                "package": packageStr,
                "signType": signType,         //微信签名方式:
                "paySign": paySign //微信签名
            }
            XCookie.doAlert("onBridgeReady params;" + JSON.stringify(params));
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', params,
                function (res) {
                    if (XCookie.isOpenVConsole()) {
                        console.log("res message=====" + JSON.stringify(res) + "========res.err_msg:" + res.err_msg)
                    }
                    // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                    if (res.err_msg == "get_brand_wcpay_request:ok") { //支付成功
                        window.location.href = "/pay/wechat/return?payOrderNum=" + payOrderNum;
                    }
                }
            );
        }
    },
    /**
     * 去支付 by 微信 在web浏览器中
     */
    toPayByWechatWeb(params) {
        let redirect = Vue.prototype.basePath() + "/pay/wechat/return?payOrderNum=" + params.payOrderNum;
        let url = params.mwebUrl + "&redirect_url=" + window.encodeURIComponent(redirect)
        window.location.href = url;
    },
//---------------------------------支付返回回调---------------------------------/
    payReturn4Zero(params) {
        window.location.href = "/pay/paySuccess/zero" + XParams.getParams(params)
    },
    payReturn4Alipay(params) {
        window.location.href = "/pay/paySuccess/ali" + XParams.getParams(params)
    },
    payReturn4Wechat(params) {
        window.location.href = "/pay/paySuccess/wechat" + XParams.getParams(params)
    }
}
